package com.ftw.commons

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity
import com.ftw.commons.utils.ClassUtils
import kotlin.properties.Delegates
import kotlin.system.exitProcess

/**
 * 描    述：
 * 作    者：fantianwen
 * 时    间：2019/2/12  10:37 AM
 */
abstract class BaseApplication : Application(), Application.ActivityLifecycleCallbacks {

    private var mDelegate: List<BaseDelegate>? = null
    var mCurrentActivityName: String = "MainActivity"


    /**
     * 获取 宿主 包名
     *
     * @return
     */
    abstract fun getApplicationId(): String


    override fun onCreate() {
        super.onCreate()
        instance = this
        registerActivityLifecycleCallbacks(this)
        mDelegate = ClassUtils.getObjectsWithInterface(
            this, BaseDelegate::class.java,
            getApplicationId()
        )

        for (delegate in mDelegate!!) {
            delegate.onCreate()
        }


    }

    companion object {

        var instance: BaseApplication by Delegates.notNull()


        private var mActivity: ArrayList<RxAppCompatActivity> = ArrayList()

        fun addActivity(activity: Activity) {
            mActivity.add(activity as RxAppCompatActivity)
        }

        fun removeActivity(activity: Activity) {
            mActivity.remove(activity as RxAppCompatActivity)
        }

        fun exitApp() {
            mActivity.forEach {
                it.finish()
            }
            exitProcess(0)
        }

        fun getTopActivity(): RxAppCompatActivity = mActivity[mActivity.size - 1]
    }


    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        for (delegate in mDelegate!!) {
            delegate.onTrimMemory(level)
        }
    }

    override fun onLowMemory() {
        super.onLowMemory()
        for (delegate in mDelegate!!) {
            delegate.onLowMemory()
        }
    }

    override fun onTerminate() {
        super.onTerminate()
        for (delegate in mDelegate!!) {
            delegate.onTerminate()
        }
    }


    override fun onActivityStarted(activity: Activity?) {
        mCurrentActivityName = activity!!.javaClass.simpleName
    }

    override fun onActivityStopped(activity: Activity?) {
    }

    override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {

    }

    override fun onActivityDestroyed(activity: Activity?) {

    }

    override fun onActivityPaused(activity: Activity?) {

    }

    override fun onActivityResumed(activity: Activity?) {

    }


    override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {

    }

}